from DrissionPage import ChromiumPage, ChromiumOptions
import time
import pandas as pd
from lxml import etree
import os  # 添加os模块用于检查文件是否存在

options = ChromiumOptions()
options.set_local_port(9222)  # 设置调试端口
page = ChromiumPage(addr_or_opts=options)

tab = page.latest_tab

tab.get('https://www.qcc.com/cassets/101716f6add519eb2b086735f705bde0.html')

time.sleep(5)


def get_html():
    qqq = tab.html
    tree = etree.HTML(qqq)
    return tree


def get_zhuanlilist(new_html):
    tree2 = etree.HTML(new_html)
    items = []
    zhuanli = []
    # print(new_html)
    Application_Number = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[1]/td[2]//text()')[0]
    Application_date = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[1]/td[4]//text()')[0]
    Ap_number = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[2]/td[2]//text()')[0]
    Ap_date = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[2]/td[4]//text()')[0]
    Aa_number = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[3]/td[2]//text()')[0]
    Aa_date = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[3]/td[4]//text()')[0]
    Priority_Number = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[4]/td[2]//text()')[0]
    priority = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[4]/td[4]//text()')[0]
    ipc_number = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[5]/td[2]//text()')[0]
    cpc_number = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[5]/td[4]//text()')[0]
    Patent_type = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[6]/td[2]//text()')[0]
    receiving_office = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[6]/td[4]//text()')[0]
    ez_legal_status = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[7]/td[2]//text()')[0]
    legal_status = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[7]/td[4]//text()')[0]
    applicant = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[8]/td[2]//text()')
    inventor = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[8]/td[4]//text()')[0]
    Address = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[9]/td[2]//text()')[0]
    agency = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[10]/td[2]//text()')[0]
    agent = tree2.xpath(
        '//div[@class="sub-part"]/table[@class="ntable"]/tr[10]/td[4]//text()')[0]
    try:
        zhuanli_abstract = tree2.xpath(
            '//div[@class="part-content"]/text()')[0]
    except:
        zhuanli_abstract = '无'
        print('没有摘要')
    try:
        Power_demand = tree2.xpath(
            '(//div[@class="part-content ea_instructions"])[1]/p/text()')
    except:
        Power_demand = '无'
        print('没有权力要求')
    # try:
    #     instructions = tree2.xpath('')
    # zhuanli.extend([Power_demand])
    # zhuanli.extend([Application_Number, Application_date, Ap_number, Ap_date, Aa_number,
    #                Aa_date, Priority_Number, priority, ipc_number, cpc_number, Patent_type, receiving_office, ez_legal_status, legal_status, applicant, inventor, Address, agency, agent])
    items.append(zhuanli)
    return items


def get_data(items):
    file_exists = os.path.exists('zhuanli.csv')
    df = pd.DataFrame(items, columns=['公司名称', '发明名称', '专利类型', '法律状态', '申请号', '申请日期',
                                      '公开号', '公开日期', '发明人'])
    df.to_csv('zhuanli.csv', mode='a',
              index=False, header=not file_exists)
    if not file_exists:
        print("创建新文件并写入表头和数据")
    else:
        print("数据已追加到 zhuanli.csv")


def get_ruanjianlist(ruanjianlist, name_h1):
    items = []
    for i in ruanjianlist:
        item_ruanjian = []
        patent_name = i.xpath('./td[2]/text()')[0]
        Patent_type = i.xpath('./td[3]/text()')[0]
        legal_status = i.xpath('./td[4]/text()')[0]
        app_number = i.xpath('./td[5]/text()')[0]
        aply_date = i.xpath('./td[6]/text()')[0]
        Publication_Number = i.xpath('./td[7]//text()')[0]
        Public_Date = i.xpath('./td[8]/text()')[0]
        inventor = i.xpath('./td[9]/text()')[0]

        item_ruanjian.extend([name_h1, patent_name, Patent_type, legal_status,
                              app_number, aply_date, Publication_Number, Public_Date, inventor])
        items.append(item_ruanjian)
    return items


def get_data1(items):
    file_exists = os.path.exists('ruanjian.csv')
    df = pd.DataFrame(items, columns=['公司名称', '软件全称', '软件简称', '版本号', '登记号', '开发完成日期',
                                      '首次发布日期', '登记日期', '权力取得方式'])
    df.to_csv('ruanjian.csv', mode='a',
              index=False, header=not file_exists)
    if not file_exists:
        print("创建新文件并写入表头和数据")
    else:
        print("数据已追加到 ruanjian.csv")


# 获取企业名称
tree1 = get_html()
name_h1 = tree1.xpath('//h1/text()')[0]


tree1 = get_html()
zhuanlilist = tree1.xpath(
    '//div[@class="data-assets"]/div[@class="company-data"]/section[@id="zhuanlilist"]/div[@class="track-table-part"]//tr[position() > 1]')
# if zhuanlilist[0]:
#     pass
while True:
    for i in range(2, len(zhuanlilist)+2):
        next_details = tab.ele(
            f'xpath://div[@class="data-assets"]/div[@class="company-data"]/section[@id="zhuanlilist"]/div[@class="track-table-part"]//tr[{i}]/td[last()]/a')
        next_details.click()
        tab.wait.load_start()
        new_tab = page.latest_tab
        new_tab_html = new_tab.html
        # 获取详细信息
        zhuanli_list = get_zhuanlilist(new_tab_html)
        print(zhuanli_list)
        break
        # try:
        #     # 等待翻页按钮加载完成
        #     tab.wait.ele_displayed(
        #         'xpath://div[@class="data-assets"]/div[@class="company-data"]/section[@id="zhuanlilist"]//ul[@class="pagination"]/li[last()]/a', timeout=10)
        #     # 获取翻页按钮
        #     next_page = tab.ele(
        #         'xpath://div[@class="data-assets"]/div[@class="company-data"]/section[@id="zhuanlilist"]//ul[@class="pagination"]/li[last()]/a')
        #     # 检查翻页按钮是否可点击
        #     next_number = tree1.xpath(
        #         '//div[@class="data-assets"]/div[@class="company-data"]/section[@id="zhuanlilist"]//ul[@class="pagination"]/li[last()]/a/text()')[0]
        #     print(next_number)
        #     if next_number != '>':
        #         break
        #     next_page.click()
        #     # 等待页面加载完成
        #     tab.wait.load_start()
        #     # 重新获取页面 HTML
        #     zhishi_html = tab.html
        #     tree1 = etree.HTML(zhishi_html)
        #     zhuanlilist = tree1.xpath(
        #         '//div[@class="data-assets"]/div[@class="company-data"]/section[@id="zhuanlilist"]/div[@class="track-table-part"]//tr[position() > 1]')
        # except Exception as e:
        #     print(f"翻页失败: {e}")
        #     break
    break

# try:
#     tree1 = get_html()
#     ruanjianlist = tree1.xpath(
#         '//div[@class="data-assets"]/div[@class="company-data"]/section[@id="rjzzqlist"]//tr[position() > 1]')
#     if ruanjianlist[0]:
#         pass
#     while True:
#         ruanjian_list = get_ruanjianlist(ruanjianlist, name_h1)
#         # print(ruanjian_list)
#         get_data1(ruanjian_list)
#         try:
#             # 等待翻页按钮加载完成
#             tab.wait.ele_displayed(
#                 'xpath://div[@class="data-assets"]/div[@class="company-data"]/section[@id="rjzzqlist"]//ul[@class="pagination"]/li[last()]/a', timeout=10)
#             # 获取翻页按钮
#             next_page = tab.ele(
#                 'xpath://div[@class="data-assets"]/div[@class="company-data"]/section[@id="rjzzqlist"]//ul[@class="pagination"]/li[last()]/a')
#             # 检查翻页按钮是否可点击
#             next_number = tree1.xpath(
#                 '//div[@class="data-assets"]/div[@class="company-data"]/section[@id="rjzzqlist"]//ul[@class="pagination"]/li[last()]/a/text()')[0]
#             # print(next_number)
#             if next_number != '>':
#                 break
#             next_page.click()
#             # 等待页面加载完成
#             tab.wait.load_start()
#             # 重新获取页面 HTML
#             ruanjian_html = tab.html
#             tree1 = etree.HTML(ruanjian_html)
#             ruanjianlist = tree1.xpath(
#                 '//div[@class="data-assets"]/div[@class="company-data"]/section[@id="rjzzqlist"]//tr[position() > 1]')
#         except Exception as e:
#             print(f"翻页失败: {e}")
#             break
# except:
#     print(f'{name_h1}没用软件著作权！！！！！！！')
